#include "messagepicker.h"
#include "ui_messagepicker.h"

MessagePicker::MessagePicker(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MessagePicker)
{
    ui->setupUi(this);

    ticketAdjustType = 0;

    model = new MessagePickerStandardItemModel();

    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);

    connect(&messageService, &MessageService::getImportMessagesSuccess,
            [=](QList<Message*> messages)
    {
        model->reset();
        model->insertMessage(messages);
        this->exec();
    });

    connect(ui->tableView, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        this->close();
        emit this->importMessageSelected(model->getMessage(index.row()));
    });
}

MessagePicker::~MessagePicker()
{
    delete ui;
}

void MessagePicker::setWidgetType(MessagePickerStandardItemModel::WidgetType widgetType){
    this->widgetType = widgetType;
    model->setWidgetType(widgetType);
    switch (widgetType) {
    case MessagePickerStandardItemModel::TicketAdjust:
        setWindowTitle("导入票款调整单");
        ui->labelTypeName->setText("导入票款调整单");
        break;
    case MessagePickerStandardItemModel::TicketIn:
        setWindowTitle("导入收票单");
        ui->labelTypeName->setText("导入收票单");
        break;
    case MessagePickerStandardItemModel::MoneyIn:
        setWindowTitle("导入收款单");
        ui->labelTypeName->setText("导入收款单");
        break;
    }
}

void MessagePicker::setTicketAdjustType(int ticketAdjustType){
    this->ticketAdjustType = ticketAdjustType;
}

void MessagePicker::showAndInit(QPushButton *button){
    messageService.getImportMessage(this, button, ticketAdjustType, widgetType);
}
